package com.ternnetwork.oa.controller.file;

import com.ternnetwork.commons.model.http.BaseResponse;
import com.ternnetwork.commons.utils.DateUtils;
import com.ternnetwork.commons.utils.ExtendedFileUtils;
import com.ternnetwork.commons.utils.JsonUtils;
import com.ternnetwork.core.accesscontroll.entity.User;
import com.ternnetwork.core.accesscontroll.service.UserService;
import com.ternnetwork.core.configuration.service.DataDictionaryService;
import com.ternnetwork.oa.dto.file.FileContent;
import com.ternnetwork.oa.dto.file.FileDto;
import com.ternnetwork.oa.dto.file.UploadFileDto;
import com.ternnetwork.oa.dto.settings.UserRelationshipDto;
import com.ternnetwork.oa.utils.Base64ToFileUtils;
import com.ternnetwork.oa.vo.file.FileVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.security.Principal;
import java.util.*;


@Controller
@RequestMapping("/file/*")
@Slf4j
public class FileController {



    @Autowired
    private UserService userService;

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @RequestMapping("/upload")
    public @ResponseBody BaseResponse upload(Principal user,String requestJson) throws Exception {

        UploadFileDto dto= JsonUtils.jsonToObjectThrowsException(requestJson, UploadFileDto.class);

        String userDirectory = getUserDirectory(user);

        String currentDirectory=dto.getCurrentDirectory();

        if(StringUtils.isEmpty(currentDirectory)){
            currentDirectory="";
        }

        String userCurrentDirectory=userDirectory.concat(currentDirectory);

        List<FileContent> fileContentList= dto.getFileContentList();

        int i=0;

        for(FileContent fileContent:fileContentList){
            //获取文件名
            String fileName = fileContent.getName();

            Base64ToFileUtils.saveBase64AsFile(fileContent.getContent().split(",")[1],fileName,userCurrentDirectory);

            i=i+1;

        }
        BaseResponse baseResponse=new BaseResponse();

        baseResponse.setSccucess();

        return baseResponse;

    }


    @RequestMapping("/list")
    public @ResponseBody BaseResponse list(Principal user,String currentDirectory){

        String userDirectory = getUserDirectory(user);

        if(StringUtils.isEmpty(currentDirectory)){
            currentDirectory="";
        }

        String userCurrentDirectory=userDirectory.concat(currentDirectory);

        File childrenFile=new File(userCurrentDirectory);

        File[] childrenFileList=childrenFile.listFiles();

        List<FileVo> fileVoList=new ArrayList<>();

        for(File file:childrenFileList){

            String name=file.getName();

            Boolean isDirectory=file.isDirectory();

            Date lastModified=new Date(file.lastModified());

            String key=currentDirectory.concat("/").concat(name);

            FileVo fileVo=new FileVo(name,currentDirectory,isDirectory,file.length(),"",DateUtils.format(lastModified,DateUtils.FORMAT_DATE_TIME_DEFAULT),key);

            fileVoList.add(fileVo);

        }

        BaseResponse baseResponse=new BaseResponse();

        baseResponse.setSccucess(fileVoList);

        return baseResponse;

    }


    @RequestMapping("/delete")
    public @ResponseBody BaseResponse delete(Principal user,String requestJson) throws Exception {

        String userDirectory = getUserDirectory(user);

        FileDto dto= JsonUtils.jsonToObjectThrowsException(requestJson, FileDto.class);

        for(String filePath:dto.getFilePaths()){

            File file=new File(userDirectory.concat(filePath));

            if(file.isDirectory()){

                ExtendedFileUtils.deleteDirectory(file);

            }else{

                ExtendedFileUtils.deleteQuietly(file);

            }
        }
        BaseResponse baseResponse=new BaseResponse();

        baseResponse.setSccucess();

        return baseResponse;

    }

    @RequestMapping("/directory/create")
    public @ResponseBody BaseResponse createDirectory(Principal user,String directoryPath) {

        String userDirectory = getUserDirectory(user);

        String userDirectoryPath=userDirectory.concat(directoryPath);

        ExtendedFileUtils.makeDirs(userDirectoryPath);

        BaseResponse baseResponse=new BaseResponse();

        baseResponse.setSccucess();

        return baseResponse;
    }

    @RequestMapping("/rename")
    public @ResponseBody BaseResponse rename(Principal user,String oldFilePath,String newFilePath){

        String userDirectory = getUserDirectory(user);

        String oldUserFilePath=userDirectory.concat(oldFilePath);

        String newUserFilePath=userDirectory.concat(newFilePath);

        BaseResponse baseResponse=new BaseResponse();

        File oldFile=new File(oldUserFilePath);

        if(oldFile.exists()!=true){
            baseResponse.setFailedForObjectNotExist();
            return  baseResponse;
        }

        oldFile.renameTo(new File(newUserFilePath));

        baseResponse.setSccucess();

        return baseResponse;
    }

    private String getUserDirectory(Principal user) {

        String[] pathList=dataDictionaryService.getValueByKey("app.oa.media.pathList").split(",");

        User loginUser= userService.findByName(user.getName());

        String userDirectory=pathList[0].concat(String.valueOf(loginUser.getId())).concat(File.separator);

        return userDirectory;
    }


}
